package work.xkong.config;

import com.alibaba.fastjson2.JSON;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import work.xkong.common.Const;
import work.xkong.common.ResponseCode;
import work.xkong.common.ResponseRest;
import work.xkong.utils.TokenUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @PACKAGE_NAME: work.xkong.config
 * @NAME: LoginInterceptor
 * @USER: NuanYang
 * @create: 2022/11/23 20:00
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 拦截登录前的操作
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        String jwt = request.getHeader("Authorization");

        log.info(jwt);

        if ("OPTIONS".equals(request.getMethod())){
            return true;
        }

        ResponseRest rr = null;

        try {
            TokenUtils.getParseToken(jwt);
        } catch (ExpiredJwtException e) {
            rr = ResponseRest.creatFail(ResponseCode.NOT_LOGIN.getCode(),"登录过期，请重新登录");
        } catch (MalformedJwtException e) {
            rr = ResponseRest.creatFail(ResponseCode.NOT_LOGIN.getCode(),"登录信息有误，请重新登录");
        } catch (SignatureException e) {
            rr = ResponseRest.creatFail(ResponseCode.NOT_LOGIN.getCode(),"a非法请求，请重新登录");
        } catch (IllegalArgumentException e) {
            rr = ResponseRest.creatFail(ResponseCode.NOT_LOGIN.getCode(),"b非法请求，请重新登录");
        }

        if (rr != null) {
            String result = JSON.toJSONString(rr);
            response.getWriter().write(result);
            return false;
        }

        return true;
    }

}
